# coding:utf-8
import shutil
import time
import tkinter as tk
import tkinter.filedialog as fileDialog
import tkinter.messagebox as msgBox
import traceback

import ttkbootstrap as tkBoot
import xlrd
from ttkbootstrap import utility
from ttkbootstrap.constants import *

from ui.add_student_box import AddStudentBox
from util.mysql_util import get_students, delete_students, add_students
from util.ui_util import create_close_btn


class StudentTab(tkBoot.Frame):
    def __init__(self, notebook, clazz):
        super().__init__(notebook)
        self.notebook = notebook
        self.clazz = clazz
        self.rowdata = get_students(fetchNameProp=False, class_id=clazz[0])
        self.studentTable = tkBoot.Treeview(
            master=self,
            bootstyle=tkBoot.INFO,
            columns=[0, 1, 2, 3],
            show=tkBoot.HEADINGS
        )

    def initFrame(self):
        create_close_btn(self, "studentTab")

        btnFrame = tkBoot.Frame(self)
        add_button = tkBoot.Button(btnFrame, text="+", command=self.open_add_box, bootstyle="success")
        add_button.pack(side=tk.LEFT, padx=(0, 10))
        delete_button = tkBoot.Button(btnFrame, text=" - ", command=self.delete_row, bootstyle="danger")
        delete_button.pack(side=tk.LEFT, padx=(0, 10))
        import_button = tkBoot.Button(btnFrame, text=" ← ", command=self.import_data, bootstyle="info")
        import_button.pack(side=tk.LEFT)
        btnFrame.pack(anchor=tk.NW, padx=(10, 100))

        tipLabel = tkBoot.Label(self, text="请不要随意删除数据！！！", bootstyle="danger")
        tipLabel.pack(side=tk.BOTTOM)

        self.create_table()
        self.insert_table_data()

        self.notebook.add(self, text=self.clazz[1])
        self.notebook.select(self)

    def create_table(self):
        self.studentTable.heading(0, text='学号', anchor=tk.CENTER)
        self.studentTable.heading(1, text='姓名', anchor=tk.W)
        self.studentTable.heading(2, text='年龄', anchor=tk.W)
        self.studentTable.column(
            column=0,
            anchor=tk.CENTER,
            width=utility.scale_size(self, 200),
            stretch=False
        )
        self.studentTable.column(
            column=1,
            anchor=tk.W,
            width=utility.scale_size(self, 250),
            stretch=False
        )
        self.studentTable.column(
            column=2,
            anchor=tk.W,
            width=utility.scale_size(self, 200),
            stretch=False
        )

        self.studentTable.pack(fill=tk.BOTH, expand=tk.YES, pady=10)

    def insert_table_data(self, rows=None):
        data = rows
        if rows is None or len(rows) <= 0:
            data = get_students(fetchNameProp=False, class_id=self.clazz[0])
        for row in data:
            self.studentTable.insert(parent="", index=END, values=row)

    def open_add_box(self):
        addStudentBox = AddStudentBox(self, self.clazz[0])
        addStudentBox.initFrame()

    def delete_row(self, cid=None):
        if cid is None:
            cid = self.studentTable.selection()
        if cid is not None:
            item = self.studentTable.item(cid, "values")
            self.studentTable.delete(cid)
            delete_students(item[0])
            time.sleep(0.1)

    def import_data(self):
        cids = self.studentTable.get_children()
        for cid in cids:
            delete_students(self.clazz[0])
            self.delete_row(cid=cid)

        studentList = self.loadStudentList()
        for row in studentList:
            add_students(row)
        self.insert_table_data()

    def loadStudentList(self) -> list:
        studentList = []
        file = fileDialog.askopenfile()
        if file is None:
            return studentList
        try:
            book = xlrd.open_workbook(file.name)
            sheet = book.sheet_by_name("学生信息")
            for i in range(0, sheet.nrows):
                student = [self.clazz[0]]
                for j in range(0, sheet.ncols):
                    if i == 0:
                        continue
                    student.append(sheet.cell_value(i, j))
                if len(student) > 1:
                    studentList.append(tuple(student))
        except shutil.Error:
            traceback.print_exc(file=open("log.txt", "a"))
            msgBox.showerror(message="您选择的excel文件有误")
        return studentList
